package com.jiamao.goplay.ui.user;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.gyf.immersionbar.ImmersionBar;
import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.adapter.UserEditPhotoAdapter;
import com.jiamao.goplay.app.AppViewModelFactory;
import com.jiamao.goplay.base.BaseMVVMFragment;
import com.jiamao.goplay.bean.res.ResUserInfoDetail;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.databinding.UserEditUserInfoBinding;
import com.jiamao.goplay.ui.photo.PhotoUploadFragment;
import com.jiamao.goplay.ui.user.vm.EditUserInfoNM;
import com.jiamao.goplay.ui.user.vm.EditUserPhotoItemVM;
import com.jiamao.goplay.ui.user.vm.UserEditPhotoAddrItemVM;
import com.jiamao.goplay.util.GlideUtils;
import com.jiamao.goplay.util.TimeUtils;
import com.jiamao.goplay.view.HorizontalItemDecoration;
import com.jiamao.goplay.view.WrapHeightGridLayoutManager;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.interfaces.OnMenuItemClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.util.DialogSettings;
import com.kongzue.dialog.v3.BottomMenu;
import com.kongzue.dialog.v3.MessageDialog;
import com.tamsiree.rxkit.view.RxToast;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.config.ISListConfig;

import java.nio.file.WatchEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import me.goldze.mvvmhabit.base.MultiItemViewModel;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.SPUtils;

/**
 * 资料编辑fragment
 */
public class UserEditUserInfoFragment extends BaseMVVMFragment<UserEditUserInfoBinding, EditUserInfoNM> {

    private int index;
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.user_edit_user_info;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public EditUserInfoNM initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(EditUserInfoNM.class);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.showPhoto.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer aBoolean) {
                index = aBoolean;
                //pSwitchObservable是boolean类型的观察者,所以可以直接使用它的值改变密码开关的图标
                showPhoto();
            }
        });

        viewModel.uc.showSex.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer aBoolean) {
                //pSwitchObservable是boolean类型的观察者,所以可以直接使用它的值改变密码开关的图标
                switch (aBoolean){
                    case 1:
                        showSexMenu();
                        break;
                    case 2:
                        showShengaoMenu();

                        break;
                    case 3:
                        showTizhongMenu();
                        break;
                    case 4:
                        showHangYeMenu();
                        break;
                    case 5:
                        showGongZuoMenu();
                        break;

                }

            }
        });

        viewModel.uc.showTime.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean aBoolean) {
                //pSwitchObservable是boolean类型的观察者,所以可以直接使用它的值改变密码开关的图标
                showTimeMenu();
            }
        });

        viewModel.uc.showUploadImg.observe(this, new Observer<EditUserPhotoItemVM>() {
            @Override
            public void onChanged(@Nullable EditUserPhotoItemVM aBoolean) {
                //pSwitchObservable是boolean类型的观察者,所以可以直接使用它的值改变密码开关的图标
                showUploadImg(aBoolean);
            }
        });

    }

    @Override
    public void initData() {
        super.initData();
        ImmersionBar.with(this). keyboardEnable(false).statusBarDarkFont(true).titleBar(binding.getRoot().findViewById(R.id.toolbar_left_right_text)).init();

        TextView titleTv =  binding.getRoot().findViewById(R.id.tv_center_title);
        titleTv.setText("编辑资料");
        binding.setAdapter(new UserEditPhotoAdapter(getContext()));
        binding.getRoot().findViewById(R.id.ll_menu).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewModel.submit();
            }
        });
        TextView textSave =    binding.getRoot().findViewById(R.id.tv_right_save);
        textSave.setText("保存");
        binding.getRoot().findViewById(R.id.tv_left_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (viewModel.checkIsEditData()){
                    showLogoutDialog();
                }else {
                    getActivity().finish();
                }

            }
        });

        WrapHeightGridLayoutManager gm = new WrapHeightGridLayoutManager(getContext(), 3);
        binding.userPhotoListView.setLayoutManager(gm);
        binding.userPhotoListView.addItemDecoration(new HorizontalItemDecoration(8,getContext()));
        gm.setAutoMeasureEnabled(true);


        String userJson = SPUtils.getInstance().getString(Config.USERINFO);
        if (TextUtils.isEmpty(userJson)){
            RxToast.showToastShort("资料读取失败");
            getActivity().finish();
            return;
        }

        ResUserInfoDetail userInfoDetail = JSONObject.parseObject(userJson, ResUserInfoDetail.class);
        if (TextUtils.isEmpty(userJson)){
            RxToast.showToastShort("资料解析失败");
            getActivity().finish();
            return;
        }
        viewModel.initLoadData(userInfoDetail);
    }

    public void showPhoto(){
        // 自由配置选项
        ISListConfig config = new ISListConfig.Builder()
                // 是否多选, 默认true
                .multiSelect(false)
                // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                .rememberSelected(false)
                // “确定”按钮背景色
                .btnBgColor(Color.GRAY)
                // “确定”按钮文字颜色
                .btnTextColor(Color.BLUE)
                // 使用沉浸式状态栏
                .statusBarColor(Color.BLACK)
                // 返回图标ResId
                .backResId(R.mipmap.icon_back)
                // 标题
                .title("图片")
                // 标题文字颜色
                .titleColor(Color.BLACK)
                // TitleBar背景色
                .titleBgColor(Color.WHITE)
                // 裁剪大小。needCrop为true的时候配置
                .cropSize(1, 1, 200, 200)
                .needCrop(false)
                // 第一个是否显示相机，默认true
                .needCamera(false)
                // 最大选择图片数量，默认9
                .maxNum(1)
                .build();

// 跳转到图片选择器
        ISNav.getInstance().toListActivity(this, config, 1);
    }


    private void showSexMenu(){
        BottomMenu.show((AppCompatActivity) getContext(), new String[]{"男", "女"}, new OnMenuItemClickListener() {
            @Override
            public void onClick(String text, int index) {
                //返回参数 text 即菜单名称，index 即菜单索引
                RxToast.showToastShort(text);
                switch (index){
                    case 0:
                        viewModel.sex.set("男");
                        //startContainerActivity(SearchFragment.class.getCanonicalName());
                        break;
                    case 1:
                        viewModel.sex.set("女");
                        break;
                    case 2:
                        //startContainerActivity(CityFragment.class.getCanonicalName());
                        break;
                }
               // aVoidData();
            }
        });
    }


    private void showShengaoMenu(){
        ArrayList<String> strings = new ArrayList<>();
        strings.add("150cm以下");
        for (int i=151;i<200;i++){
            strings.add(i+"cm");
        }
        strings.add("200cm以上");
        String[] integers = strings.toArray(new String[strings.size()]);
        BottomMenu.show((AppCompatActivity) getContext(), integers, new OnMenuItemClickListener() {
            @Override
            public void onClick(String text, int index) {
                //返回参数 text 即菜单名称，index 即菜单索引
                viewModel.sg.set(text);
                // aVoidData();
            }
        });
    }


    private void showTizhongMenu(){
        BottomMenu.show((AppCompatActivity) getContext(),new String[]{"40kg以下", "40-45kg", "45-50kg", "50-55kg", "55-60kg", "60-65kg",
                "65-70kg", "70-75kg", "75-80kg", "80-85kg", "85-90kg", "90-99kg", "95-100kg"}, new OnMenuItemClickListener() {
            @Override
            public void onClick(String text, int index) {
                //返回参数 text 即菜单名称，index 即菜单索引
                viewModel.tz.set(text);
            }
        });
    }

    private void showHangYeMenu(){
        BottomMenu.show((AppCompatActivity) getContext(),new String[]{"学生", "文化/艺术", "影视/娱乐", "金融", "医药/健康", "工业/制造业",
                "IT/互联网/通信", "媒体/公关", "零售业", "教育/科研", "其他"}, new OnMenuItemClickListener() {
            @Override
            public void onClick(String text, int index) {
                viewModel.hy.set(text);
            }
        });
    }

    private void showGongZuoMenu(){
        //创始人、高管、职业经理人、咨询顾问、市场、产品、客服、销售、商务、公关、人事、行政、财务、法务、工程师、设计、运营、编辑、分析师、翻译、科研人员、其他
        BottomMenu.show((AppCompatActivity) getContext(), new String[]{"创始人", "高管", "职业经理人", "咨询顾问", "市场", "产品",

                "客服", "销售", "商务", "公关", "人事", "行政", "财务", "法务", "工程师", "设计", "运营", "编辑", "分析师", "翻译", "科研人员", "其他"}, new OnMenuItemClickListener() {
            @Override
            public void onClick(String text, int index) {

                viewModel.zw.set(text);
            }
        });
    }


    private void showTimeMenu(){

        Calendar selectedDate = Calendar.getInstance();//系统当前时间

        Calendar startDate = Calendar.getInstance();
        startDate.set(1900, 1, 23);

        Calendar endDate = Calendar.getInstance();
        endDate.set(2000, 1, 1);





        TimePickerView pvTime = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                //Toast.makeText(getContext(), date., Toast.LENGTH_SHORT).show();
              //  viewModel.constellation.set(TimeUtils.getTime(date)+" "+TimeUtils.getAstro(date));
               // viewModel.birthday.set(TimeUtils.getTime(date));
                viewModel.sz.set(TimeUtils.getAstro(date));
                viewModel.birthday.set(TimeUtils.getTime(date));
               // aVoidData();
            }
        }).       setDate(selectedDate)
                .setRangDate(startDate,selectedDate)
                .build();
        pvTime.show();
    }


    private void showUploadImg(EditUserPhotoItemVM avatarList){
        if (avatarList!=null){
            if (avatarList.avatarList.getType() == 0){

                if (viewModel.isTouXiangRenzh == 1){
                    //创始人、高管、职业经理人、咨询顾问、市场、产品、客服、销售、商务、公关、人事、行政、财务、法务、工程师、设计、运营、编辑、分析师、翻译、科研人员、其他
                    BottomMenu.show((AppCompatActivity) getContext(), new String[]{"更换认证头像"}, new OnMenuItemClickListener() {
                        @Override
                        public void onClick(String text, int index) {
                            switch (index) {
                                case 0:
                                    int i = 0;
                                    for (MultiItemViewModel itemViewModel : viewModel.observableListImage) {
                                        if (((EditUserPhotoItemVM) itemViewModel) == avatarList) {
                                            UserEditUserInfoFragment.this.index = i;
                                            break;
                                        }
                                        i++;
                                    }
                                    showPhoto();
                                    break;
                                case 1:
                                    //  viewModel.observableListImage.remove(avatarList);
                                    break;
                                case 2:
                                    break;
                            }
                            // viewModel.zw.set(text);
                        }
                    });
                }else {
                    showUserPhotoDialog(avatarList.imgUrl.get());
                }

            }
            else {
                //中铝系统门窗
                //创始人、高管、职业经理人、咨询顾问、市场、产品、客服、销售、商务、公关、人事、行政、财务、法务、工程师、设计、运营、编辑、分析师、翻译、科研人员、其他
                BottomMenu.show((AppCompatActivity) getContext(), new String[]{"更换照片","删除照片"}, new OnMenuItemClickListener() {
                    @Override
                    public void onClick(String text, int index) {
                        switch (index){
                            case 0:
                                int  i= 0;
                               for(MultiItemViewModel itemViewModel:viewModel.observableListImage){
                                   if (((EditUserPhotoItemVM)itemViewModel)  == avatarList){
                                       UserEditUserInfoFragment.this.index = i;
                                       break;
                                   }
                                   i++;
                               }
                                showPhoto();
                                break;
                            case 1:
                                KLog.d("删除aaaaa");
                                viewModel.observableListImage.remove(avatarList);
                                MultiItemViewModel item2 = new UserEditPhotoAddrItemVM(viewModel,0);
                                //条目类型为右布局
                                item2.multiItemType("add");
                                viewModel.observableListImage.add(item2);
//                                viewModel.observableListImage.
//                                viewModel.observableListIm
                                break;
                            case 2:
                                break;
                        }//  viewModel.zw.set(text);
                    }
                });
            }
        }

    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 图片选择结果回调
        if (requestCode ==  1  && data != null) {
            List<String> pathList = data.getStringArrayListExtra("result");

            viewModel.index = index;


            Bundle bd = new Bundle();
            bd.putString("img",pathList.get(0));
            bd.putInt("from",2);
            bd.putInt("type",index==0?1:0);
            startContainerActivity(PhotoUploadFragment.class.getCanonicalName(),bd);

           // viewModel.uploadImage(pathList.get(0),index);

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Messenger.getDefault().unregister(this);
    }
    
    
    void showUserPhotoDialog(String url){
        View view = View.inflate(getContext(), R.layout.app_update_photo_dialog_custom, null);
        ImageView imgUser = view.findViewById(R.id.img_user);

        GlideUtils.loadImageView(getContext(),url,imgUser);

        final Button btnUpgrade = view.findViewById(R.id.btn_dialog_custom_upgrade);
        final Button clacen = view.findViewById(R.id.clacen);
        AlertDialog dialog = new AlertDialog.Builder(getContext())
                .setView(view)
                .create();
        btnUpgrade.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPhoto();
                index = 0;
                dialog.dismiss();
            }
        });
        clacen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                //   client.remove();
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                // client.remove();
            }
        });
        dialog.show();
    }



    void showLogoutDialog(){

        MessageDialog.build((AppCompatActivity) getContext())
                .setStyle(DialogSettings.STYLE.STYLE_IOS)
                .setTitle("资料还未保存")
                .setMessage("是否保存")
                .setOkButton("保存", new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                            viewModel.submit();
                        //AppApplication.getInstance().startLogins();
                        return false;
                    }

                }).setCancelButton("不保存", new OnDialogButtonClickListener() {
            @Override
            public boolean onClick(BaseDialog baseDialog, View v) {
                   getActivity().finish();
                //AppApplication.getInstance().startLogins();
                return false;
            }

        })
                .show();

    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK){
            if (viewModel.checkIsEditData()){
                showLogoutDialog();
            }else {
                getActivity().finish();
            }
            return true;
        }
        return false;
    }

}
